package com.apache.funds.service.plugins;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.funds.entity.SvmCaptionBalance;
import com.apache.funds.entity.SvmUser;
import com.apache.funds.manager.SvmCaptionBalanceManager;
import com.apache.funds.manager.SvmUserManager;
import com.apache.funds.util.Constants;
import com.apache.funds.util.FundsTemplate;
import com.apache.tools.DateUtils;
import com.apache.tools.DateUtils.FmtStr;
import com.apache.tools.StrUtil;

/**  
 * 账号开户，修改信息同步
 * @author xhe 创建时间：2015-12-05         
 */
public class FundsOpenAccountPlugin implements PluginConnector {
	private Logger log = LoggerFactory.getLogger(getClass());

	private SvmUserManager svmUserManager;
	private SvmCaptionBalanceManager svmCaptionBalanceManager;

	@Override
	public Object execute(ParamsVo arg0) throws Exception {
		ResultEntity entity = new ResultEntity();
		entity.setResult("true");
		entity.setMessage(Constants.Msg.F001);
		entity.setEntity("false");
		
		
		Map<String, String> prarmMap = arg0.getParams();
		//校验参数

		String userEname = prarmMap.get("userEname");
		if (Validator.isNull(userEname)) {
			entity.setMessage(Constants.Msg.F003);
			return entity;
		}
		String userId = prarmMap.get("userId");
		String userCname = prarmMap.get("userCname");
		String certCode = prarmMap.get("certCode");
		String certType = prarmMap.get("certType");
		String mobile = prarmMap.get("mobile");
		String contactUser = prarmMap.get("contactUser");
		String contactAddress = prarmMap.get("contactAddress");
		String passWord = prarmMap.get("password");//补充密码口令参数
		String createUser = prarmMap.get("createUser");//创建人账号
		String createUserName = prarmMap.get("createUserName");//创建人名称
		
		String bankType = prarmMap.get("bankType");// 银行行别
		String bankAccount = prarmMap.get("bankAccount");// 银行账户
		String bound = prarmMap.get("bound");// 和银行绑定签约状态（null未绑，0绑定，1暂停，2解绑）

//		ParamsVo<SvmUser> vo = new ParamsVo<SvmUser>();
//		SvmUser userVo = new SvmUser();
//		userVo.setUsername(userEname);
//		vo.setObj(userVo);
//		List<SvmUser> list = svmUserManager.getList(vo);
		
		ParamsVo<SvmUser> voU = new ParamsVo<SvmUser>();
		SvmUser userOld = null;
		if (StrUtil.isNotNull(userId)) {
			voU.setInfoId(userId);
			userOld = (SvmUser)svmUserManager.getInfoById(voU);
		}else {
			voU.setParams("userName", userEname);
			voU.setMethodKey("ByUserName");
			userOld = (SvmUser)svmUserManager.execute(voU);
		}
		SvmUser user = null;
		String resultStr = "";
		if (userOld !=null) {
			user = userOld;
			user.setUserName(userEname);
			user.setRealName(userCname);
			user.setCertiFicate(certCode);
			user.setCertiType(certType);
			user.setMobile(mobile);
			user.setContactUser(contactUser);
			user.setContactAddress(contactAddress);
			user.setCreateUser(createUser);
			user.setCreateUserName(createUserName);
			user.setBankAccount(bankAccount);
			user.setBankType(bankType);
			user.setBound(bound);
			ParamsVo<SvmUser> voSave = new ParamsVo<SvmUser>();
			voSave.setObj(user);
			svmUserManager.editInfo(voSave);
			resultStr = user.getUserId()+","+user.getUserName()+",账户修改完成";
		} else {
			user = new SvmUser();
			if (StrUtil.isNotNull(userId)) {
				user.setUserId(userId);
			}
			user.setUserName(userEname);
			user.setRealName(userCname);
			user.setPassWord(passWord);
			user.setCertiFicate(certCode);
			user.setCertiType(certType);
			user.setMobile(mobile);
			user.setContactUser(contactUser);
			user.setContactAddress(contactAddress);
			user.setCreateUser(createUser);
			user.setCreateUserName(createUserName);
			user.setBankAccount(bankAccount);
			user.setBankType(bankType);
			user.setBound(bound);
			user.setCreateTime(DateUtils.format(DateUtils.getDate(), FmtStr.yyyyMMdd_HHmmss.toString()));
			ParamsVo<SvmUser> voSave = new ParamsVo<SvmUser>();
			voSave.setObj(user);
			svmUserManager.saveInfo(voSave);
			resultStr = user.getUserId()+","+user.getUserName()+",账户创建完成";
			
			//初始化期初表（按照科目记录一条昨日的期初信息）
			addCaptionBalances(userEname);
		}
		
		log.info(resultStr);
		entity.setEntity(JSONObject.fromObject(user));
		entity.setMessage(resultStr);
		return entity;
	}
	
	
	/**
	 * 初始化对应用户的昨日余额到，期初余额表中，保证开通后就可以立即查看余额；
	 * @param userId 资金账号
	 * @param nextDate 
	 * @return
	 */
	private void addCaptionBalances(String userId){
		List<FundsTemplate> listTemplates = Constants.getAllCaptionTemplate();//模板list
		long lastDate = getYesterday(DateUtils.getDate());
		
		log.info("开户初始化用户["+userId+"]期初表，设置昨日余额为零...");
		for (FundsTemplate temp : listTemplates) {
			SvmCaptionBalance scbtmp = new SvmCaptionBalance();
			scbtmp.setCaptionId(temp.getCaption());//补充科目
			scbtmp.setUserId(userId);
			scbtmp.setBalance(0l);//默认为0
			scbtmp.setDateTrade(lastDate);
			
			
			ParamsVo<SvmCaptionBalance> vo = new ParamsVo<SvmCaptionBalance>();
			vo.setObj(scbtmp);
			try {
				String d = svmCaptionBalanceManager.saveInfo(vo);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取指定日期上一天的 yyyyMMdd的毫秒数
	 * @param date
	 * @return
	 */
	private static long getYesterday(Date date){
		Date dateTradeYesterday = DateUtils.beforeNDays(date, 1);//前一天日期时间
		try {
			long dty = DateUtils.parse(DateUtils.format(dateTradeYesterday, FmtStr.yyyyMMdd.toString())).getTime();
			return dty;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0l;
	}
	
	
	

	public void setSvmUserManager(SvmUserManager svmUserManager) {
		this.svmUserManager = svmUserManager;
	}

	public void setSvmCaptionBalanceManager(SvmCaptionBalanceManager svmCaptionBalanceManager) {
		this.svmCaptionBalanceManager = svmCaptionBalanceManager;
	}
}
